package cn.edu.wfit.gateway.filter;

import cn.edu.wfit.common.core.constant.CacheConstants;
import cn.edu.wfit.common.core.constant.HttpStatus;
import cn.edu.wfit.common.core.constant.SecurityConstants;
import cn.edu.wfit.common.core.constant.TokenConstants;
import cn.edu.wfit.common.core.utils.JwtUtils;
import cn.edu.wfit.common.core.utils.ServletUtils;
import cn.edu.wfit.common.core.utils.StringUtils;
import cn.edu.wfit.common.redis.service.RedisService;
import cn.edu.wfit.gateway.config.properties.AuthProperties;
import com.alibaba.fastjson2.JSONObject;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthGlobalFilter.class);
    private final AuthProperties authProperties;
    private final RedisService redisService;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        URI uri = request.getURI();
        if(isExcludePaths(uri)){
            return chain.filter(exchange);
        }
        String token = getToken(request);
        if (StringUtils.isEmpty(token))
        {
           // return writeResponse(exchange.getResponse(),HttpStatus.UNAUTHORIZED,"令牌不能为空");
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null)
        {
           // return writeResponse(exchange.getResponse(),402,"Token已过期或者Token错误");
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确！");
        }
        String userkey = JwtUtils.getUserKey(claims);
        boolean islogin = redisService.hasKey(getTokenKey(userkey));
        if (!islogin)
        {
           // return writeResponse(exchange.getResponse(),HttpStatus.UNAUTHORIZED,"登录状态已过期");
            return unauthorizedResponse(exchange, "登录状态已过期");
        }
        String userid = JwtUtils.getUserId(claims);
        String username = JwtUtils.getUserName(claims);
        String nickname = JwtUtils.getNickName(claims);
        String usertype = JwtUtils.getUserType(claims);
        if (StringUtils.isEmpty(userid) || StringUtils.isEmpty(username) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(usertype))
        {
           // return writeResponse(exchange.getResponse(),HttpStatus.UNAUTHORIZED,"令牌验证失败");
            return unauthorizedResponse(exchange, "令牌验证失败");
        }

       /* exchange.mutate().request(builder -> builder.header(SecurityConstants.USER_KEY, userkey)).build();
        exchange.mutate().request(builder -> builder.header(SecurityConstants.DETAILS_USER_ID, userid)).build();
        exchange.mutate().request(builder -> builder.header(SecurityConstants.DETAILS_USERNAME, username)).build();
        exchange.mutate().request(builder -> builder.header(SecurityConstants.DETAILS_NICKNAME, nickname)).build();
        exchange.mutate().request(builder -> builder.header(SecurityConstants.DETAILS_USER_TYPE, usertype)).build();
        // 内部请求来源参数清除
        exchange.mutate().request(builder -> builder.headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM_SOURCE))).build();
        //exchange.getRequest().mutate().headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM_SOURCE)).build();

        return chain.filter(exchange);*/
        // 设置用户信息到请求
        addHeader(mutate, SecurityConstants.USER_KEY, userkey);
        addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);
        addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
        addHeader(mutate, SecurityConstants.DETAILS_NICKNAME, nickname);
        addHeader(mutate, SecurityConstants.DETAILS_USER_TYPE, usertype);
        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value)
    {
        if (value == null)
        {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name)
    {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg)
    {
        log.error("[鉴权异常处理]请求路径:{},错误信息:{}", exchange.getRequest().getPath(), msg);
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
    }
    /**
     * 构建返回内容
     *

     * @return Mono
     */
/*    protected Mono<Void> writeResponse(ServerHttpResponse response, Integer code, String msg) {
        JSONObject message = new JSONObject();
        message.put("code", code);
        message.put("msg", msg);
        byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(org.springframework.http.HttpStatus.OK);
        // 指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }*/
    private boolean isExcludePaths(URI uri) {
        String path = uri.getPath();
        List<String> excludePaths = authProperties.getExcludePaths();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String excludePath : excludePaths) {
            boolean match = antPathMatcher.match(excludePath, path);
            if(match){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
    /**
     * 获取缓存key
     */
    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
        {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }
}
